<template>
  <div class="app-container">
    <div class="view-title">管理员管理</div>

    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true">
      <el-form-item label="用户名">
        <el-input
          v-model="queryParams.username"
          placeholder="请输入用户名"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="昵称">
        <el-input
          v-model="queryParams.nick"
          placeholder="请输入昵称"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
      </el-form-item>
    </el-form>
    <el-row :gutter="10">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-permission="['admin:add']"
          >新增</el-button
        >
      </el-col>
    </el-row>
    <el-table
      :data="tableData"
      v-loading="loading"
      element-loading-text="正在加载中"
      :header-cell-style="{
        borderColor: '#F0F0F0',
        height: '51px',
        background: '#F0F0F0',
        color: '#333',
      }"
      :row-style="{ height: '51px' }"
      :cell-style="{ borderColor: '#F0F0F0' }"
      style="width: 100%; margin-top: 20px"
    >
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="username" label="用户名" />
      <el-table-column prop="nick" label="昵称" />

      <el-table-column prop="created_at" label="创建时间" />
      <el-table-column prop="prop" label="操作" width="300">
        <template slot-scope="{ row }">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(row)" 
            v-permission="['admin:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handlePassword(row)"
            v-permission="['admin:editPassword']"
            >修改密码</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleReset(row)"
            v-permission="['admin:reset']"
            >重置密码</el-button
          >

          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(row)"
            v-permission="['admin:delete']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="totalRows > 0"
      :total="totalRows"
      :page.sync="queryParams.pageNow"
      :limit.sync="queryParams.pageSize"
      @pagination="loadData"
    />
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="500px"
      append-to-body
      :before-close="cancel"
    >
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="24" v-if="dialogType !== 'pass'">
            <el-form-item label="用户名">
              <el-input
                v-model="form.username"
                placeholder="请输入用户名"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24" v-if="dialogType !== 'pass'">
            <el-form-item label="昵称">
              <el-input
                v-model="form.nick"
                placeholder="请输入用户名"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24" v-if="dialogType === 'edit'">
            <el-form-item label="分配角色">
              <el-select v-model="form.role_ids" placeholder="">
                <el-option
                  v-for="i in roleList"
                  :key="i.id"
                  :label="i.name"
                  :value="i.id.toString()"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24" v-if="dialogType === 'add'">
            <el-form-item label="密码">
              <el-input
                v-model="form.password"
                placeholder="请输入密码"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24" v-if="dialogType === 'pass'">
            <el-form-item label="旧密码">
              <el-input
                v-model="form.old_password"
                placeholder="请输入旧密码"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24" v-if="dialogType === 'pass'">
            <el-form-item label="新密码">
              <el-input
                v-model="form.new_password"
                placeholder="请输入新密码"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getAdminList,
  addAdmin,
  getAdmin,
  updateAdmin,
  updateAdminPassword,
  deleteAdmin,
  resetAdminPassword,
  getRoleList,
} from "@/api/role";
export default {
  data() {
    return {
      roleList: [],
      loading: false,
      dialogType: "edit",
      totalRows: 0,
      queryParams: {
        username: "",
        nick: "",
        pageNow: 1,
        pageSize: 10,
      },
      form: {
        username: "",
        nick: "",
        password: "",
        role_ids: "",
        old_password: "",
        new_password: "",
      },
      // 表单校验
      rules: {
        menuName: [
          { required: true, message: "菜单名称不能为空", trigger: "blur" },
        ],
        orderNum: [
          { required: true, message: "菜单顺序不能为空", trigger: "blur" },
        ],
        path: [
          { required: true, message: "路由地址不能为空", trigger: "blur" },
        ],
      },
      title: "",
      open: false,
      tableData: [],
    };
  },
  created() {
    this.loadData();
    this.getRoleList();
  },
  methods: {
    getRoleList() {
      getRoleList().then((res) => {
        this.roleList = res.data;
      });
    },
    /** 查询管理员列表 */
    loadData() {
      getAdminList(this.queryParams).then((response) => {
        this.tableData = response.data;
        this.totalRows = response.page_info.total_count;
      });
    },
    handleQuery() {
      this.loadData();
    },
    submitForm() {
      this.$refs["formRef"].validate((valid) => {
        if (valid) {
          if (this.dialogType === "edit") {
            updateAdmin(this.form).then((response) => {
              this.$message.success("修改成功");
              this.open = false;
              this.loadData();
            });
          } else if (this.dialogType === "add") {
            addAdmin(this.form).then((response) => {
              this.$message.success("新增成功");
              this.open = false;
              this.loadData();
            });
          } else {
            updateAdminPassword(this.form).then((res) => {
              this.$message.success("修改成功");
              this.open = false;
              this.loadData();
            });
          }
        }
      });
    },
    cancel() {
      this.open = false;
      this.reset();
    },

    handleAdd() {
      this.dialogType = "add";
      this.open = true;
      this.title = "新增管理员";
      this.form = this.$options.data().form;
    },
    handleUpdate(row) {
      this.dialogType = "edit";
      this.form = this.$options.data().form;
      getAdmin(row.id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改管理员";
      });
    },
    handlePassword(row) {
      this.dialogType = "pass";
      this.form = this.$options.data().form;
      this.form.id = row.id;
      this.open = true;
      this.title = "修改密码";
    },
    handleDelete(row) {
      this.$confirm("是否确认删除？")
        .then(() => {
          deleteAdmin({ ids: row.id }).then((res) => {
            this.loadData();
            this.$message.success("删除成功");
          });
        })
        .catch(() => {});
    },
    handleReset(row) {
      this.$confirm("是否重置为默认密码？")
        .then(() => {
          resetAdminPassword({ id: row.id }).then((res) => {
            this.loadData();
            this.$message.success("删除成功");
          });
        })
        .catch(() => {});
    },
    // 表单重置
    reset() {
      this.form = this.$options.data().form;
      this.$refs["formRef"].clearValidate();
    },
  },
};
</script>

<style lang="scss" scoped>
.role-container {
  height: 500px;
  overflow-y: auto;
  &::-webkit-scrollbar-track-piece {
    background: #d3dce6;
  }

  &::-webkit-scrollbar {
    width: 6px;
  }

  &::-webkit-scrollbar-thumb {
    background: #99a9bf;
    border-radius: 20px;
  }
}
</style>
